import apiClient from '../api'

// OCR服务类型枚举
export enum OcrServiceType {
  ALIYUN = 'aliyun',
  BAIDU = 'baidu', 
  TESSERACT = 'tesseract',
  PPOCR = 'ppocr',
  MOCK = 'mock'
}

// OCR配置接口
export interface OcrConfig {
  accessKeyId?: string
  accessKeySecret?: string
  endpoint?: string
  region?: string
  serviceType: OcrServiceType
  baiduApiKey?: string
  baiduSecretKey?: string
  useFallback: boolean
}

// OCR识别结果接口
export interface OcrResult {
  success: boolean
  text: string
  confidence: number
  words?: Array<{
    text: string
    confidence: number
    location?: {
      left: number
      top: number
      width: number
      height: number
    }
  }>
  error?: string
}

// 医疗身份信息接口
export interface MedicalIdInfo {
  name: string
  id: string
  department?: string
  position?: string
  licenseNumber?: string
  hospitalName?: string
  phoneNumber?: string
  emergencyContact?: string
}

// 药物信息接口
export interface DrugInfo {
  name: string
  specification?: string
  manufacturer?: string
  batchNumber?: string
  productionDate?: string
  expiryDate?: string
  approvalNumber?: string
  ingredients?: string
  usage?: string
  dosage?: string
  storage?: string
  category?: string
  indication?: string // 适应症
}

// 获取OCR配置
export const getOcrConfig = async (): Promise<OcrConfig> => {
  const response = await apiClient.get('/ocr/config')
  return response.data
}

// 更新OCR配置
export const updateOcrConfig = async (config: Partial<OcrConfig>): Promise<void> => {
  await apiClient.post('/ocr/config', config)
}

// 通用OCR文字识别
export const recognizeText = async (imageFile: File): Promise<OcrResult> => {
  const formData = new FormData()
  formData.append('image', imageFile)
  
  const response = await apiClient.post('/ocr/recognize', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  
  return response.data
}

// 医生身份证识别
export const recognizeDoctorId = async (imageFile: File): Promise<MedicalIdInfo> => {
  const ocrResult = await recognizeText(imageFile)
  
  // 解析医生身份证信息
  const parsedInfo = parseDoctorIdInfo(ocrResult?.text || '')
  return parsedInfo
}

// 病人身份证识别
export const recognizePatientId = async (imageFile: File): Promise<MedicalIdInfo> => {
  const ocrResult = await recognizeText(imageFile)
  
  // 解析病人身份证信息
  const parsedInfo = parsePatientIdInfo(ocrResult?.text || '')
  return parsedInfo
}

// 药物标签识别 - 使用专门的药物识别接口
export const recognizeDrugLabel = async (imageFile: File, useParallel: boolean = false): Promise<DrugInfo & { recognitionInfo?: any }> => {
  const formData = new FormData()
  formData.append('image', imageFile)
  formData.append('parallel', useParallel.toString())
  
  const response = await apiClient.post('/ocr/recognize/drug', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  
  // 返回解析后的药物信息和识别详情
  const drugInfo = response.data.data.drugInfo || parseDrugInfo(response.data.data.text)
  return {
    ...drugInfo,
    recognitionInfo: {
      confidence: response.data.data.confidence,
      service: response.data.data.service,
      recognitionMode: response.data.data.recognitionMode,
      fusedFrom: response.data.data.fusedFrom
    }
  }
}

// 解析医生身份证信息的辅助函数
const parseDoctorIdInfo = (text: string): MedicalIdInfo => {
  // 这里实现医生身份证信息解析逻辑
  // 可以使用正则表达式来提取姓名、证件号等信息
  
  // 安全检查
  if (!text || typeof text !== 'string') {
    return {
      name: '',
      id: ''
    }
  }
  
  const nameMatch = text.match(/姓名[：:]\s*([^\s\n]+)/)
  const idMatch = text.match(/证件号[：:]\s*([A-Za-z0-9]+)/)
  const deptMatch = text.match(/科室[：:]\s*([^\s\n]+)/)
  const positionMatch = text.match(/职位[：:]\s*([^\s\n]+)/)
  const licenseMatch = text.match(/执业证号[：:]\s*([A-Za-z0-9]+)/)
  
  return {
    name: nameMatch ? nameMatch[1] : '',
    id: idMatch ? idMatch[1] : '',
    department: deptMatch ? deptMatch[1] : '',
    position: positionMatch ? positionMatch[1] : '',
    licenseNumber: licenseMatch ? licenseMatch[1] : ''
  }
}

// 解析病人身份证信息的辅助函数
const parsePatientIdInfo = (text: string): MedicalIdInfo => {
  // 这里实现病人身份证信息解析逻辑
  
  // 安全检查
  if (!text || typeof text !== 'string') {
    return {
      name: '',
      id: ''
    }
  }
  
  const nameMatch = text.match(/姓名[：:]\s*([^\s\n]+)/)
  const idMatch = text.match(/身份证号[：:]\s*([0-9X]{18})/)
  const phoneMatch = text.match(/电话[：:]\s*([0-9-+\s]+)/)
  const emergencyMatch = text.match(/紧急联系人[：:]\s*([^\s\n]+)/)
  
  return {
    name: nameMatch ? nameMatch[1] : '',
    id: idMatch ? idMatch[1] : '',
    phoneNumber: phoneMatch ? phoneMatch[1] : '',
    emergencyContact: emergencyMatch ? emergencyMatch[1] : ''
  }
}

// 解析药物信息的辅助函数
const parseDrugInfo = (text: string): DrugInfo => {
  // 这里实现药物标签信息解析逻辑
  
  // 安全检查
  if (!text || typeof text !== 'string') {
    return {
      name: ''
    }
  }
  
  // 清理文本，去除多余空格和特殊字符
  const cleanText = text.replace(/\s+/g, ' ').trim()
  
  // 多种模式匹配药品名称
  let nameMatch = cleanText.match(/[药品]*名称[：:]\s*([^\s\n]+)/)
  if (!nameMatch) {
    // 尝试匹配胶囊、片剂、颗粒等常见药品形式
    nameMatch = cleanText.match(/([\u4e00-\u9fa5]+(?:胶囊|片|颗粒|口服液|注射液|软膏|滴眼液))/)
  }
  if (!nameMatch) {
    // 尝试匹配"复方xxx"形式
    nameMatch = cleanText.match(/(复方[\u4e00-\u9fa5]+(?:胶囊|片|颗粒|口服液))/)
  }
  
  // 匹配国药准字号
  const approvalMatch = cleanText.match(/国药准字([H|Z|S|B|T|F][0-9]{8})/) || 
                       cleanText.match(/批准文号[：:]\s*([A-Za-z0-9]+)/)
  
  // 其他字段的匹配
  const specMatch = cleanText.match(/规格[：:]\s*([^\s\n]+)/)
  const manufacturerMatch = cleanText.match(/生产企业[：:]\s*([^\s\n]+)/)
  const batchMatch = cleanText.match(/批号[：:]\s*([A-Za-z0-9]+)/)
  const productionMatch = cleanText.match(/生产日期[：:]\s*([0-9-/.年月日]+)/)
  const expiryMatch = cleanText.match(/有效期[：:至]\s*([0-9-/.年月日]+)/)
  const ingredientsMatch = cleanText.match(/成分[：:]\s*([^\n]+)/)
  const usageMatch = cleanText.match(/用法[：:]\s*([^\n]+)/)
  const dosageMatch = cleanText.match(/用量[：:]\s*([^\s\n]+)/)
  const storageMatch = cleanText.match(/贮藏[：:]\s*([^\n]+)/)
  
  // 尝试提取适应症信息
  const indicationMatch = cleanText.match(/适应症.*?适用于([^。]+)/) ||
                         cleanText.match(/【适应症】([^【]+)/)
  
  return {
    name: nameMatch ? nameMatch[1] : '',
    specification: specMatch ? specMatch[1] : '',
    manufacturer: manufacturerMatch ? manufacturerMatch[1] : '',
    batchNumber: batchMatch ? batchMatch[1] : '',
    productionDate: productionMatch ? productionMatch[1] : '',
    expiryDate: expiryMatch ? expiryMatch[1] : '',
    approvalNumber: approvalMatch ? approvalMatch[1] : '',
    ingredients: ingredientsMatch ? ingredientsMatch[1] : '',
    usage: usageMatch ? usageMatch[1] : '',
    dosage: dosageMatch ? dosageMatch[1] : '',
    storage: storageMatch ? storageMatch[1] : '',
    indication: indicationMatch ? indicationMatch[1].trim() : '' // 添加适应症字段
  }
}

// 模拟数据生成函数（用于开发测试）
export const generateMockDrugInfo = (): DrugInfo => ({
  name: '阿莫西林胶囊',
  specification: '0.25g×12粒',
  manufacturer: '华北制药股份有限公司',
  batchNumber: 'A2024001',
  productionDate: '2024-01-15',
  expiryDate: '2027-01-14',
  approvalNumber: '国药准字H13020959',
  ingredients: '阿莫西林',
  usage: '口服',
  dosage: '成人一次0.5g，一日3次',
  storage: '密封，在干燥处保存',
  category: '抗生素'
})

export const generateMockDoctorInfo = (): MedicalIdInfo => ({
  name: '张医生',
  id: 'DOC001',
  department: '内科',
  position: '主治医师',
  licenseNumber: 'L110020240001',
  hospitalName: '第一人民医院',
  phoneNumber: '138-8888-0001',
  emergencyContact: '李护士 139-9999-0001'
})

export const generateMockPatientInfo = (): MedicalIdInfo => ({
  name: '李患者',
  id: '110101199001010001',
  phoneNumber: '138-8888-0002',
  emergencyContact: '王女士 139-9999-0002',
  hospitalName: '第一人民医院'
})